<template>
  <div>
    <form-content
      :rules="formItems2Rules"
      :form-items="formItems"
      :submitApi="detail.id ? update : add"
      :afterSubmit="afterSubmit"
      :beforeSubmit="beforeSubmit"
      :formStateInit="detail"
    >
      <template #business_license="{ item, formState }">
        <div class="">
          <Uploader v-model:value="formState.business_license" :maxLen="1" />
        </div>
      </template>
    </form-content>
  </div>
</template>

<script>
  import { ref, toRefs, reactive, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { formItems, formItems2Rules } from './config';
  import { add, update, info } from './api';
  import { message } from 'ant-design-vue';

  export default {
    data() {
      return {
        add,
        update,
        info,
        formItems,
        formItems2Rules,
      };
    },
    setup(props, context) {
      const route = useRoute();
      const router = useRouter();
      const state = reactive({
        detail: {},
      });
      const geiDetail = () => {
        info({
          id: parseInt(route.params.id),
        }).then((res) => {
          state.detail = {
            ...res.data,
            area: [
              res.data.province_id,
              res.data.city_id,
              res.data.district_id,
            ],
            business_license: [res.data.business_license],
          };
        });
      };

      onMounted(() => {
        if (route.params.id) {
          geiDetail();
        } else {
          state.detail = {};
        }
      });
      const afterSubmit = (res) => {
        message.success('操作成功');
        router.push('/space/company');
      };

      const beforeSubmit = (params) => {
        if (route.params.id) {
          params.id = parseInt(route.params.id);
        }
        params.business_license = params.business_license[0];
        params.province_id = params.area[0];
        params.city_id = params.area[1];
        params.district_id = params.area[2];
        delete params.area;
        return params;
      };

      return {
        beforeSubmit,
        afterSubmit,
        ...toRefs(state),
      };
    },
  };
</script>
